package com.woniuxy.job;

import cn.hutool.core.util.ReUtil;
import com.woniuxy.mapper.LogMapper;
import com.woniuxy.service.LogService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @BelongsProject: quartzStudy
 * @BelongsPackage: com.woniuxy.job
 * @Author: Quan
 * @Date: 2025/3/4 16:56
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Component
public class MyJob implements Job {
	@Resource
	LogMapper logMapper;

	@Value("${quartz.cron-exception}")
	private String cronException;

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// context: 定时任务执行的环境
		// 获取jobDetail
		JobDetail jobDetail = context.getJobDetail();
		// 记录任务执行次数
		JobDataMap jobDataMap = jobDetail.getJobDataMap();
		Integer count = (Integer) jobDataMap.get("count");
		System.out.println("第" + count + "次执行");
		jobDataMap.put("count", ++count);

		LocalDateTime now = LocalDateTime.now();
		System.out.println("---------------------------------------------------------");
		System.out.println("---------------------------------------------------------");
		System.out.println("---------------------------------------------------------");

		// 获取该时间之前的时间
		Integer logRetention = logMapper.queryLogRetention("simple_log");

		// 计算30天前的时间
		LocalDateTime thirtyDaysAgo = now.minusDays(logRetention);

		// 格式化输出
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		System.out.println(thirtyDaysAgo.format(formatter));
		logMapper.delLog(thirtyDaysAgo.format(formatter));
	}
}
